class AdGroupsController < ApplicationController
  before_action :set_ad_group, only: [:destroy,:edit,:update]
  def index
      sql = <<-SQL
        select a.*,sum(b.view_num) as view_num,sum(b.click_num) as click_num,sum(b.cost) as cost from ad_groups a
        left join ad_group_rpts b on a.id = b.ad_group_id
        where a.user_id = #{current_user.id} group by a.id
      SQL
    @ad_group_rpts = AdGroup.where(user_id: current_user.id).left_joins(:ad_group_rpts).group(:id).select('ad_groups.*,sum(ad_group_rpts.view_num) as view_num,sum(ad_group_rpts.click_num) as click_num,sum(ad_group_rpts.cost) as cost').paginate(page: params[:page]).order(created_at: :desc)
      #@ad_group_rpts = AdGroup.order(created_at: :desc).find_by_sql(sql).paginate(page: params[:page])
  end

  def edit
    @ad_group_ceative_rels = @ad_group.ad_group_creative_rels
  end

  def update
   respond_to do |format|
      if @ad_group.update_attributes( title: params[:title], ad_put_type: params[:adPutType], ad_put_start_at: params[:adPutStartAt],ad_put_end_at: params[:adPutEndAt], ad_offer: params[:adOffer])
        @ad_group.ad_group_creative_rels.delete
        @ad_group.ad_group_creative(params[:creativesId],@ad_group.id)
        format.html { redirect_to @ad_group  }
        format.json { render json: @ad_group }
      else
        format.html { render :new }
        format.json { render json: @ad_group }
      end
    end
  end


  def new
    @ad_group = AdGroup.new
  end

  def destroy
    @ad_group.destroy
    flash[:success] = "删除成功"
    redirect_to request.referrer || ad_group_path
  end

  def create
    campaign = current_user.campaigns.where(campaign_type: params[:frontCampaignType]).first
    @ad_group = AdGroup.create(user_id: session[:user_id],campaign_id: campaign.id ,campaign_type: params[:frontCampaignType], title: params[:title],ad_put_type: params[:adPutType], ad_put_start_at: params[:adPutStartAt],ad_put_end_at: params[:adPutEndAt], ad_offer: params[:adOffer])
    respond_to do |format|
      if @ad_group.save
        @ad_group.ad_group_creative_rels.delete
        @ad_group.ad_group_creative(params[:creativesId],@ad_group.id)
        format.html { redirect_to @ad_group  }
        format.json { render json: @ad_group ,status: :ok}
      else
        format.html { render :new }
        format.json { render json: @ad_group }
      end
    end

  end

  def set_ad_group
    @ad_group = AdGroup.find(params[:id])
  end

end
